import threading
import time

# 创建两个锁对象
lock_a = threading.Lock()
lock_b = threading.Lock()


def thread_1():
    print("线程1: 尝试获取锁A...")
    with lock_a:
        print("线程1: 已获取锁A，等待1秒...")
        time.sleep(1)

        print("线程1: 尝试获取锁B...")
        with lock_b:
            print("线程1: 已获取锁A和锁B")


def thread_2():
    print("线程2: 尝试获取锁B...")
    with lock_b:
        print("线程2: 已获取锁B，等待1秒...")
        time.sleep(1)

        print("线程2: 尝试获取锁A...")
        with lock_a:
            print("线程2: 已获取锁B和锁A")


# 创建并启动线程
t1 = threading.Thread(target=thread_1)
t2 = threading.Thread(target=thread_2)

t1.start()
t2.start()

# 等待线程结束
t1.join()
t2.join()

print("程序结束")  # 这行实际上永远不会执行，因为发生了死锁